package com.leyou.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leyou.common.pojo.R;
import com.leyou.common.utils.GenerateNumber;
import com.leyou.mall.data.entity.MallGoods;
import com.leyou.mall.data.entity.MallGoodsPicture;
import com.leyou.mall.data.entity.MallSpecs;
import com.leyou.mall.service.MallGoodsPictureService;
import com.leyou.mall.service.MallGoodsService;
import com.leyou.mall.service.MallSpecsService;
import com.leyou.order.data.dto.OrderGoodsDto;
import com.leyou.order.data.entity.OrderGoods;
import com.leyou.order.data.entity.OrderGoodsItem;
import com.leyou.order.data.vo.OrderGoodsPayVo;
import com.leyou.order.mapper.OrderGoodsMapper;
import com.leyou.order.mapper.OrderShoppingCartMapper;
import com.leyou.order.service.OrderGoodsItemService;
import com.leyou.order.service.OrderGoodsService;
import com.leyou.rabbitmq.OrderRabbitMq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xhh
 * @since 2022-07-04
 */
@Slf4j
@RestController
@RequestMapping("/leyou.order/order-goods")
public class OrderGoodsController{
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private MallSpecsService mallSpecsService;
    @Autowired
    private OrderShoppingCartMapper orderShoppingCartMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MallGoodsService mallGoodsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MallGoodsPictureService mallGoodsPictureService;


    @Autowired
    private OrderGoodsItemService orderGoodsItemService;
    /**
    * todo 下单
    * @param 
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/15 15:02
    * @deprecated 没有加优惠信息，实际支付金额，优惠金额
    */
    @Transactional
    @RequestMapping(value = "/createGoodsOrder",method = RequestMethod.POST)
    public R createGoodsOrder(@RequestBody List<OrderGoodsItem> orderGoodsItemList){
        Set set=new HashSet();
        QueryWrapper queryWrapper=new QueryWrapper();
        //将生成的s作为父订单number
        String fatherNumber=GenerateNumber.getNumber(null);
        //下单时间
        Date orderDate=new Date();
        //父订单购买数量
        Integer amount=0;
        //父订单实际支付金额
        BigDecimal flowPrice=new BigDecimal(0);
        //父订单应该支付的金额
        BigDecimal orderPrice=new BigDecimal(0);
        //订单项
        OrderGoods orderGoods=new OrderGoods();
        orderGoods.setOrderTime(orderDate);
        orderGoods.setState(2);
        orderGoods.setNumber(fatherNumber);
        orderGoods.setUserId(orderGoodsItemList.get(0).getUserId());
        orderGoods.setMailId(orderGoodsItemList.get(0).getMailId());

        for (OrderGoodsItem goodsItem : orderGoodsItemList) {
            MallSpecs mallSpecs = mallSpecsService.getById(goodsItem.getSkuId());
            MallGoods mallGoods = mallGoodsService.getById(goodsItem.getSpuId());
            String skuName = orderGoodsMapper.getSkuName(goodsItem.getSkuId());

            queryWrapper.clear();
            queryWrapper.eq("goods_id",goodsItem.getSpuId());
            queryWrapper.eq("main_pic",1);
            MallGoodsPicture mallGoodsPicture = mallGoodsPictureService.getOne(queryWrapper);

            goodsItem.setNumber(GenerateNumber.getNumber(null));

            set.add(goodsItem.getNumber());

            BigDecimal price =  mallSpecs.getPrice();
            //计算金额
            goodsItem.setGoodsPrice(price.multiply(new BigDecimal(goodsItem.getAmount())));
            //下单时间
            goodsItem.setOrderTime(orderDate);
            //状态 待付款
            goodsItem.setState(1);
            //父编号
            goodsItem.setFatherNumber(fatherNumber);
            //商品图片
            goodsItem.setGoodsImage(mallGoodsPicture.getUrl());
            //商品name
            goodsItem.setGoodsName(mallGoods.getName());
            //商品sku name 拼接
            goodsItem.setGoodsSkuName(skuName);
            //购物车 删除下单的商品
            Boolean i = orderShoppingCartMapper.realDelete(goodsItem.getCartId());
            /*锁库存*/
            mallSpecs.setStockLock(mallSpecs.getStockLock()+goodsItem.getAmount());
            mallSpecsService.updateById(mallSpecs);

            //父订单操作
            amount+=goodsItem.getAmount();
            orderPrice=orderPrice.add(goodsItem.getGoodsPrice());
        }

        SetOperations SetOperations = redisTemplate.opsForSet();
        for (Object o : set) {
            SetOperations.add(fatherNumber,o);
        }
        /*存储订单*/
        boolean saveBatch = orderGoodsItemService.saveBatch(orderGoodsItemList);
        /*存储父订单*/
        orderGoods.setAmount(amount);
        orderGoods.setOrderPrice(orderPrice);
        orderGoodsService.save(orderGoods);
        if(saveBatch) {
            log.info("rabbitmq 发送{}",fatherNumber);
            rabbitTemplate.convertAndSend(OrderRabbitMq.ORDER_EXCHANGE,OrderRabbitMq.ROUTING_KEY,fatherNumber);
            return R.ok().data("orders",fatherNumber);
        }
        else {
            return R.error();
        }
    }

    ///**
    //* todo 跳转支付前，将cartNumber 关联的 所有orderNumber存入redis
    //* @param
    //* @return com.leyou.common.pojo.R
    //* @author xhh
    //* @data 2022/7/22 17:11
    //* @deprecated
    //*/
    //@Transactional
    //@RequestMapping(value = "/GoodsOrderPay",method = RequestMethod.POST)
    //public R GoodsOrderPay(){
    //
    //}
    /**
    * todo 完成支付
    * @param ordersKey
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/19 20:24
    * @deprecated 
    */
    @Transactional
    @RequestMapping(value = "/paymentDone",method = RequestMethod.POST)
    public R paymentDone(@RequestParam("ordersKey")String ordersKey){
        /*假设调用支付接口查看是否支付成功  代码省略…………*/
        Set range = redisTemplate.opsForSet().members(ordersKey);
        LambdaQueryWrapper<OrderGoodsItem> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<OrderGoods> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<MallSpecs> lambdaQueryWrapper3=new LambdaQueryWrapper<>();
        Boolean f=true;
        Integer i=0;
        //修改订单项
        OrderGoods orderGoods = orderGoodsService.getOne(lambdaQueryWrapper2);
        orderGoods.setState(1);
        boolean bb = orderGoodsService.updateById(orderGoods);
        //修改每一条订单
        for (Object orderNumber : range ) {
            System.err.println(orderNumber);
            i++;
            lambdaQueryWrapper1.clear();
            lambdaQueryWrapper1.eq(OrderGoodsItem::getNumber,orderNumber);
            OrderGoodsItem one = orderGoodsItemService.getOne(lambdaQueryWrapper1);
            one.setState(2);
            boolean b1 = orderGoodsItemService.updateById(one);

            /*减少库存 放锁*/
            MallSpecs byId = mallSpecsService.getById(one.getSkuId());
            byId.setStockLock(byId.getStockLock()-one.getAmount());
            byId.setStock(byId.getStock()-one.getAmount());
            boolean b2 = mallSpecsService.updateById(byId);
            if(!b1 && !b2){
                f=false;
            }
        }if(i==0){
            f=false;
        }if(f && bb){
            return R.ok();
        }else{
            return R.error();
        }
    }
    /**
    * todo 待付款/待收货/待发货/待评价
    * @param userId
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/20 16:25
    * @deprecated  -1-已退款,0-已申请退款,1-待付款,2-待发货,3-待收货,4-待评价,5-已评价
    */
    @RequestMapping(value = "/waitOrderState",method = RequestMethod.POST)
    public R waitOrderState(@RequestParam("userId")Integer userId,@RequestParam("state")Integer state){
        if(state==1){
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("user_id",userId);
            //1-已支付,2-未支付,3-已超时,4-已取消
            queryWrapper.eq("state",2);
            List<OrderGoods> orderGoodsList = orderGoodsService.list(queryWrapper);
            List<OrderGoodsPayVo> payVos=new ArrayList<>();
            for (OrderGoods goods : orderGoodsList) {
                queryWrapper.clear();
                queryWrapper.eq("father_number",goods.getNumber());
                //-2 订单已过期,-1-已退款,0-已申请退款,1-待付款,2-待发货,3-待收货,4-待评价,5-已评价
                queryWrapper.eq("state",1);
                List<OrderGoodsItem> list=orderGoodsItemService.list(queryWrapper);
                OrderGoodsPayVo vo=new OrderGoodsPayVo();
                List<String> picUrls=new ArrayList<>();
                for (OrderGoodsItem goodsItem : list) {
                    OrderGoodsDto orderGoodsDtos = orderGoodsMapper.orderById(goodsItem.getId());
                    picUrls.add(orderGoodsDtos.getPicUrl());
                }
                vo.setCartNumber(goods.getNumber());
                vo.setPicUrls(picUrls);
                vo.setTotalAmount(goods.getAmount());
                vo.setTotalPrice(goods.getOrderPrice());
                payVos.add(vo);
            }
            if(payVos.size()>0){
                return R.ok().data("list",payVos);
            }else{
                return R.error();
            }

        }else{
            List<OrderGoodsDto> orderGoodsDtos = orderGoodsMapper.waitOrderState(userId, state);
            return R.ok().data("list",orderGoodsDtos);
        }

    }
    /**
    * todo 取消订单
    * @param cartNumber
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/20 19:21
    * @deprecated  根据order id 删除订单 并解除锁定的库存
    */
    @Transactional
    @RequestMapping(value = "/cancelOrder",method = RequestMethod.POST)
    public R cancelOrder(@RequestParam("cartNumber")String cartNumber){
        int f=0;
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("number",cartNumber);
        OrderGoods orderGoods=orderGoodsService.getOne(queryWrapper);
        orderGoods.setState(4);
        boolean b1 = orderGoodsService.updateById(orderGoods);
        queryWrapper.clear();
        queryWrapper.eq("father_number",cartNumber);
        List<OrderGoodsItem> list = orderGoodsItemService.list(queryWrapper);
        for (OrderGoodsItem goodsItem : list) {
            Integer orderId=goodsItem.getId();
            //解除锁定的库存
            MallSpecs mallSpecs = mallSpecsService.getById(goodsItem.getSkuId());
            mallSpecs.setStockLock(mallSpecs.getStockLock()-goodsItem.getAmount());
            boolean save = mallSpecsService.updateById(mallSpecs);
            //删除订单
            boolean b = orderGoodsItemService.removeById(orderId);
            if(b && save){
                f++;
            }
        }
        if(f==list.size()){
            return R.ok();
        }else{
            return R.error();
        }
    }
    /**
    * todo 支付回查
    * @param cartNumber
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/22 16:32
    * @deprecated
    */
    @Transactional
    @RequestMapping(value = "/waitPay",method = RequestMethod.POST)
    public R waitPay(@RequestParam("cartNumber")String cartNumber){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("number",cartNumber);
        OrderGoods orderGoods=orderGoodsService.getOne(queryWrapper);
        List<OrderGoodsDto> orderGoodsDtos = orderGoodsMapper.orderByCartNumber(cartNumber);
        //BigDecimal multiply=new BigDecimal(0);
        //for (OrderGoodsDto cartGoodsDto : orderGoodsDtos) {
        //    BigDecimal multiply1 = cartGoodsDto.getGoodsPrice().multiply(new BigDecimal(cartGoodsDto.getAmount()));
        //    //System.out.println(multiply1);
        //    multiply=multiply.add(multiply1);
        //}
        return R.ok().data("list",orderGoodsDtos).data("totalPrice",orderGoods.getOrderPrice()).data("mailId",orderGoods.getMailId());
    }
    /**
    * todo 支付订单
    * @param orderId
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/20 19:23
    * @deprecated 修改order_goods state ,商品库存和锁库存减少,
    */
    //@Transactional
    //@RequestMapping(value = "/paymentOrder",method = RequestMethod.POST)
    //public R paymentOrder(@RequestParam("id")Integer orderId){
    //    //修改order_goods state
    //    OrderGoods orderGoods=new OrderGoods();
    //    orderGoods.setState(1);
    //    orderGoods.setPayTime(new Date());
    //    LambdaQueryWrapper<OrderGoods> queryWrapper=new LambdaQueryWrapper<>();
    //    queryWrapper.eq(OrderGoods::getId,orderId);
    //    boolean update = orderGoodsService.update(orderGoods, queryWrapper);
    //    //商品库存和锁库存减少,
    //    OrderGoods byId = orderGoodsService.getById(orderId);
    //    MallSpecs byId1 = mallSpecsService.getById(byId.getSkuId());
    //    byId1.setStockLock(byId1.getStockLock()-byId.getAmount());
    //    byId1.setStock(byId1.getStock()-byId.getAmount());
    //    boolean save = mallSpecsService.updateById(byId1);
    //
    //    if(update && save){
    //        return R.ok();
    //    }else{
    //        return R.error();
    //    }
    //}
    /**
    * todo 申请退款
    * @param orderId
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/20 19:37
    * @deprecated 修改order_goods state
    */
    @RequestMapping(value = "/applyRefund",method = RequestMethod.POST)
    public R applyRefund(@RequestParam("id")Integer orderId){
        OrderGoodsItem byId = orderGoodsItemService.getById(orderId);
        byId.setState(0);
        boolean b = orderGoodsItemService.updateById(byId);
        if(b){
            return R.ok();
        }else{
            return R.error();
        }
    }
    /**
    * todo 确认收货
    * @param orderId
    * @return com.leyou.common.pojo.R
    * @author xhh
    * @data 2022/7/20 19:41
    * @deprecated 修改order_goods state, mall_goods 增加数量
    */
    @Transactional
    @RequestMapping(value = "/takeGoods",method = RequestMethod.POST)
    public R takeGoods(@RequestParam("id")Integer orderId){
        //修改order_goods_item state
        OrderGoodsItem orderGoodsItem = orderGoodsItemService.getById(orderId);
        orderGoodsItem.setState(4);
        boolean b = orderGoodsItemService.updateById(orderGoodsItem);
        //mall_goods 增加数量
        MallGoods mallGoods = mallGoodsService.getById(orderGoodsItem.getSpuId());
        mallGoods.setBuyCount(mallGoods.getBuyCount()+orderGoodsItem.getAmount());
        boolean b1 = mallGoodsService.updateById(mallGoods);
        if(b && b1){
            return R.ok();
        }else{
            return R.error();
        }
    }

}

